package com.ruoyi.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.exam.domain.ExamBankQuestion;
import com.ruoyi.exam.domain.ExamQuestionBank;
import com.ruoyi.exam.vo.BankProgressInfoVo;
import com.ruoyi.exam.vo.ExamQuestionBankVo;
import com.ruoyi.exam.vo.WeeklyCheckInVo;
import com.ruoyi.exam.vo.ExamUserPracticeRecordVo;
import com.ruoyi.exam.mapper.ExamBankQuestionMapper;
import com.ruoyi.exam.mapper.ExamQuestionBankMapper;
import com.ruoyi.exam.mapper.ExamUserPracticeRecordMapper;
import com.ruoyi.exam.service.IExamQuestionBankService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题库Service业务层处理
 *
 * @author Tellsea
 * @date 2025-05-30
 */
@Service
public class ExamQuestionBankServiceImpl extends ServiceImpl<ExamQuestionBankMapper, ExamQuestionBank> implements IExamQuestionBankService {

    @Autowired
    private ExamUserPracticeRecordMapper examUserPracticeRecordMapper;

    @Autowired
    private ExamBankQuestionMapper examBankQuestionMapper;

    @Override
    public TableDataInfo<ExamQuestionBankVo> queryList(ExamQuestionBankVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<ExamQuestionBankVo> queryAll(ExamQuestionBankVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public ExamQuestionBankVo queryById(Long bankId) {
        return this.baseMapper.queryById(bankId);
    }

    @Override
    public List<ExamQuestionBankVo> myCategoryList(ExamQuestionBankVo entity, Long userId) {
        List<ExamQuestionBankVo> list = this.baseMapper.myCategoryList(entity, userId);
        return list;
    }

    @Override
    public List<ExamQuestionBankVo> myQuestionBankList(Long userId) {
        List<ExamQuestionBankVo> list = this.baseMapper.myQuestionBankList(userId);
        for(ExamQuestionBankVo bank : list) {
            //通过examBankQuestionMapper,统计每个题库的题目数量
            Integer questionCount = examBankQuestionMapper.selectCount(new QueryWrapper<ExamBankQuestion>().lambda().eq(ExamBankQuestion::getBankId, bank.getBankId()));
            bank.setQuestionCount(Long.valueOf(questionCount));
        }
        return list;
    }

    @Override
    public BankProgressInfoVo getBankProgressInfo(Long bankId, Long userId) {
        return this.baseMapper.getBankProgressInfo(bankId, userId);
    }

    @Override
    public Long getStudyDays(Long bankId, Long userId) {
        return this.baseMapper.getStudyDays(bankId, userId);
    }

    @Override
    public WeeklyCheckInVo getWeeklyCheckIn(Long userId) {
        // 获取本周的开始和结束日期（周一到周日）
        LocalDate today = LocalDate.now();
        LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startDate = startOfWeek.format(formatter);
        String endDate = endOfWeek.format(formatter);
        
        // 查询本周答题记录
        List<Map<String, Object>> checkInData = this.baseMapper.getWeeklyCheckIn(userId, startDate, endDate);
        
        // 将查询结果转换为Map，方便查找
        Map<String, Integer> dateCountMap = checkInData.stream()
            .collect(Collectors.toMap(
                map -> map.get("practice_date").toString(),
                map -> ((Number) map.get("question_count")).intValue()
            ));
        
        // 构建本周七天的打卡信息
        List<WeeklyCheckInVo.DailyCheckInVo> dailyCheckIns = new ArrayList<>();
        String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        
        int checkInDays = 0;
        int continuousDays = 0;
        int maxContinuousDays = 0;
        
        for (int i = 0; i < 7; i++) {
            LocalDate currentDate = startOfWeek.plusDays(i);
            String dateStr = currentDate.format(formatter);
            
            WeeklyCheckInVo.DailyCheckInVo dailyCheckIn = new WeeklyCheckInVo.DailyCheckInVo();
            dailyCheckIn.setDate(dateStr);
            dailyCheckIn.setDayOfWeek(i + 1);
            dailyCheckIn.setDayOfWeekText(weekDays[i]);
            
            Integer questionCount = dateCountMap.get(dateStr);
            boolean isCheckedIn = questionCount != null && questionCount > 0;
            
            dailyCheckIn.setIsCheckedIn(isCheckedIn);
            dailyCheckIn.setQuestionCount(questionCount != null ? questionCount : 0);
            
            dailyCheckIns.add(dailyCheckIn);
            
            // 统计打卡天数和连续打卡天数
            if (isCheckedIn) {
                checkInDays++;
                continuousDays++;
                maxContinuousDays = Math.max(maxContinuousDays, continuousDays);
            } else {
                continuousDays = 0;
            }
        }
        
        // 构建返回对象
        WeeklyCheckInVo result = new WeeklyCheckInVo();
        result.setDailyCheckIns(dailyCheckIns);
        result.setCheckInDays(checkInDays);
        result.setContinuousDays(maxContinuousDays);
        
        return result;
    }

    @Override
    public Map<String, Object> getUserAnswerStats(Long bankId, Long userId) {
        // 查询用户在该题库的所有答题记录
        List<ExamUserPracticeRecordVo> practiceRecords = examUserPracticeRecordMapper.getByUserIdAndBankId(userId, bankId);
        
        // 初始化统计变量
        long totalAnswerCount = 0;
        long correctAnswerCount = 0;
        long studiedCount = practiceRecords.size(); // 已学习数量（答题记录列表的长度）
        
        // 循环计算统计信息
        for (ExamUserPracticeRecordVo record : practiceRecords) {
            // 只统计正常状态的记录
            if ("1".equals(record.getStatus())) {
                totalAnswerCount++;
                // 统计正确答题数
                if ("1".equals(record.getIsCorrect())) {
                    correctAnswerCount++;
                }
            }
        }
        
        // 计算正确率
        double accuracyRate = 0.0;
        if (totalAnswerCount > 0) {
            accuracyRate = (double) correctAnswerCount / totalAnswerCount * 100;
            // 保留2位小数
            accuracyRate = Math.round(accuracyRate * 100.0) / 100.0;
        }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("studied_count", studiedCount); // 已学习数量
        result.put("total_answer_count", totalAnswerCount);
        result.put("correct_answer_count", correctAnswerCount);
        result.put("accuracy_rate", accuracyRate);
        
        return result;
    }
}
